package com.clark.dingding.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.clark.dingding.interfaces.NewsItemClickCallBack
import com.clark.dingding.model.NewsData
import com.linkage.linkedlife.R
import com.linkage.linkedlife.databinding.ItemNewsBinding

/**
 * Created by Clark on 2020-1-12
 */
class NewsAdapter
/**
 * 构造方法传入点击监听器
 * @param itemClickCallback
 */(var newsItemClickCallback: NewsItemClickCallBack?) :
    RecyclerView.Adapter<NewsAdapter.GirlsViewHolder>() {
    var newsList: List<NewsData.ResultBean>? = null
    fun setGirlsList(list: List<NewsData.ResultBean>) {
        if (newsList == null) {
            newsList = list
            notifyItemRangeInserted(0, newsList!!.size)
        } else {
            val diffResult = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
                override fun getOldListSize(): Int {
                    return newsList!!.size
                }

                override fun getNewListSize(): Int {
                    return list.size
                }

                override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                    val oldData = newsList!![oldItemPosition]
                    val newData = list[newItemPosition]
                    return oldData.id === newData.id
                }

                override fun areContentsTheSame(
                    oldItemPosition: Int,
                    newItemPosition: Int
                ): Boolean {
                    val oldData = newsList!![oldItemPosition]
                    val newData = list[newItemPosition]
                    return oldData.id === newData.id && oldData.createdAt === newData.createdAt && oldData.publishedAt === newData.publishedAt && oldData.source === newData.source
                }
            })
            newsList = list
            diffResult.dispatchUpdatesTo(this)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GirlsViewHolder {
        val binding: ItemNewsBinding = DataBindingUtil
            .inflate(
                LayoutInflater.from(parent.context), R.layout.item_news,
                parent, false
            )
        binding.callback = newsItemClickCallback
        return GirlsViewHolder(binding)
    }

    override fun onBindViewHolder(holder: GirlsViewHolder, position: Int) {
        holder.binding.newItem = newsList!![position]
        holder.binding.executePendingBindings()
    }

    override fun getItemCount(): Int {
        return if (newsList == null) 0 else newsList!!.size
    }

    class GirlsViewHolder(var binding: ItemNewsBinding) : RecyclerView.ViewHolder(binding.root)
}